import { Vec3 } from "./Vec3";

class Frustum{
    constructor(matrix){
        this.matrix=matrix;
        this.planes=[new Plane(),new Plane(),new Plane(),new Plane(),new Plane(),new Plane()];
    }
    build(matrix){
        if(!matrix)
            return false;
        const planes = this.planes;
		const me0 = matrix[ 0 ], me1 = matrix[ 1 ], me2 = matrix[ 2 ], me3 = matrix[ 3 ];
		const me4 = matrix[ 4 ], me5 = matrix[ 5 ], me6 = matrix[ 6 ], me7 = matrix[ 7 ];
		const me8 = matrix[ 8 ], me9 = matrix[ 9 ], me10 = matrix[ 10 ], me11 = matrix[ 11 ];
		const me12 = matrix[ 12 ], me13 = matrix[ 13 ], me14 = matrix[ 14 ], me15 = matrix[ 15 ];
		planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
		planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
		planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
		planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
		planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
		planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
		return this;
    }
    getVertices(){
        if(!this.matrix)
            return false;
        const vertices = [];
		const vpInvert = this.matrix.clone().invert();
		
		// 定义标准化设备坐标（NDC）的 8 个角点
		const ndcCorners = [
		  new Vec3([-1, -1, -1]), // 近左下
		  new Vec3([1, -1, -1]),  // 近右下
		  new Vec3([1, 1, -1]),   // 近右上
		  new Vec3([-1, 1, -1]),  // 近左上
		  new Vec3([-1, -1, 1]),  // 远左下
		  new Vec3([1, -1, 1]),   // 远右下
		  new Vec3([1, 1, 1]),    // 远右上
		  new Vec3([-1, 1, 1])    // 远左上
		];
	  
		// 将 NDC 坐标转换到世界空间
		for (let i = 0; i < ndcCorners.length; i++) {
		  const corner = ndcCorners[i].clone();
		  corner.transformMat4(vpInvert); // 转换到世界空间
		  vertices.push(corner.x, corner.y, corner.z);
		}
		return vertices;
    }
}
export {Frustum}